const Koa = require('koa');
const koaBody = require('koa-body');
const schedule = require('node-schedule');
const router = require('koa-router')();
const { createMain, saveLog } = require('./common/operate');
const myurl = process.argv[3] || 'https://luciano233.gitee.io';
const port = process.argv[2] || 80;
var fn_upload = require('./api/upload');
var fn_download = require('./api/download');
var fn_delete = require('./api/delete');
var fn_create = require('./api/createdir');
var fn_rmdir = require('./api/rmdir');
global.mylog = [];

const app = new Koa();
createMain();

app.use(async (ctx, next) => {
    var allowedOrigins = ['http://luciano233.gitee.io', myurl];
    var origin = ctx.headers.origin;
    if (allowedOrigins.indexOf(origin) > -1) {
        ctx.set('Access-Control-Allow-Origin', origin);
    }
    // ctx.set('Access-Control-Allow-Origin', myurl);//访问控制允许来源：*为所有
    ctx.set('Access-Control-Allow-Headers', 'mytoken')
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200; //OPTIONS类型的请求直接返回200
    } else {
        await next();
    }
});

app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 5 * 1024 * 1024
    }
}));

router.get('/create/:id', fn_create)
router.get('/rmdir/:id/:time', fn_rmdir)
router.get('/download/:id/:time/:name', fn_download)
router.get('/delete/:id/:time/:name', fn_delete)
router.post('/uploadfile', fn_upload)

app.use(router.routes());

(() => { schedule.scheduleJob('0 0 4 * * *', saveLog); })()

app.listen(port);
console.log(`app started at port ${port}...`);